import {Component, Input, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {ActivatedRoute, Router} from "@angular/router";
import {ProcessService} from "../process.service";
import {StorageService} from "../../services/storage.service";
import {ConfirmationService, Message} from "primeng/primeng";
import {environment} from "../../../environments/environment";
import {timeValidator} from "../../validator/validators";
import {EventBusService} from "../../services/event-bus.service";

@Component({
  selector: 'app-construction-management',
  templateUrl: './construction-application.component.html',
  styleUrls: ['./construction-application.component.scss']
})
export class ConstructionApplicationComponent implements OnInit {
  zh;
  cols;
  submitData;
  initStartTime: Date;
  showAddEquement : boolean = false;
  dataSource = [];
  inspections ;
  personalData = [];
  message: Message[] = [];               // 交互提示弹出框
  displayPersonel: boolean = false;
  displayLocation: boolean = false;
  displayaffectLocation:boolean = false;
  brand: string;
  totalRecords;
  selectConstructions = [];
  statusNames;
  categories ;
  radioButton = [];
  type;//判断是申请人还是审批人
  viewState;
  constructionData=[];
  ip;
  editDataSource = [];
  editInspections;
  file;
  treeModel;
  updatetreeModel;
  constructionForm : FormGroup;
  construction_plantime_start:Date;                   // 当日系统时间
  construction_plantime_end: Date;
  nowDate;
  tableDatas;
  dropDownData;
  updatedropDownData;
  sid;
  chooseCids;
  MaxDate: Date;
  maxdate;
  @Input() room :String ;
  constructionLocation = [];
  affectLocation = [];
  location = [];
  affected_location = [];
  public construct_location: String;
  con_ocation;
  aff_location;
  constructor(
    private route: ActivatedRoute,
    private router:Router,
    private processService:ProcessService,
    private storageService: StorageService,
    private confirmationService: ConfirmationService,
    private fb: FormBuilder,
    private eventBusService: EventBusService

  ) {
    this.constructionForm = this.fb.group({
      'sid': [''],
      'status':[''],
      'creator': [],
      'create_time': [''],
      'submitter': ['', Validators.required],
      'submit_time': [''],
      'submitter_org': [''],
      'submitter_phone': [''],
      'construction_type': ['',Validators.required],
      'org_approver': [''],
      'is_affected': [''],
      'affected_plantime_begin': [''],
      'construct_location': ['',Validators.required],
      'affected_location': [''],
      'construction_content': [''],
      'construction_description': ['',Validators.required],
      'construction_affecttime_start': [''],
      'construction_affecttime_end': [''],
      timeGroup:this.fb.group({
        startTime: ['', Validators.required],
        endTime: ['', Validators.required],
      },{validator:timeValidator}),
    });
  }

  ngOnInit() {

    this.construction_plantime_start = new Date();
    this.construction_plantime_end = new Date();
    this.nowDate = new Date();
    // this.maxdate = this.submitData.construction_plantime_end;
    this.radioButton = [
      {label:'影响业务',value:true},
      {label:'不影响业务',value:false}
      ];
    this.treeModel={
      oid:""
    }
    this.updatetreeModel={
      oid:''
    }
    this.initStartTime = new Date();
    this.zh = {
      firstDayOfWeek: 1,
      dayNames: [ "周一","周二","周三","周四","周五","周六","周日" ],
      dayNamesShort: [ "一","二","三","四","五","六","七" ],
      dayNamesMin: [ "一","二","三","四","五","六","七" ],
      monthNames: [ "一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月" ],
      monthNamesShort: [ "一","二","三","四","五","六","七","八","九","十","十一","十二" ],
    };
    this.statusNames = [
      {label:'新建',value:'新建'},
    ]
    this.cols = [
      {field: 'ano', header: '设备编号'},
      {field: 'name', header: '设备名称'},
      {field: 'modle', header: '设备型号'},
      {field: 'location', header: '设备位置'},
      {field: 'manager', header: '责任人'},
      {field: 'status', header: '设备状态'},
    ];
    this.submitData = {
      "status": this.statusNames[0]['value'],  //状态
      "creator":'',    //受理人
      "create_time":this.processService.getFormatTime(),   //受理时间
      "submitter":'',   //申请人
      "submitter_pid":'',   //申请人账号
      "submit_time":this.processService.getFormatTime(), //申请时间
      "submitter_org":'',  //所属组织
      "submitter_org_oid":'',  //所属组织
      "construction_plantime_start":'', //计划开始时间
      "submitter_phone":'', //电话
      "construction_plantime_end":'', //计划结束时间
      "construction_types":[],//施工类型
      "construct_location":[],//施工区域
      "org_approver":'', //部门审批人
      "org_approver_pid":'', //部门审批人
      "is_affected":'', //影响业务
      "construction_affecttime_start":'', //影响开始时间
      "construction_affecttime_end":'', //影响结束时间
      "affectLocation":[], //影响区域
      "construction_content":'', //施工内容
      "construction_description":'', //施工详述
      "construction_apply_attachments":[], //上传附件
      "devices":[], //关联设备

    };
    this.ip = environment.url.management;
    this.route.queryParams.subscribe(params =>{
      this.viewState = 'add';
      if(params['sid']&&params['state'] && params['title']){
        this.viewState = params['state'];
        this.sid = params['sid'];
        this.processService.constructionShow(params['sid']).subscribe(data=>{
          this.constructionData = data;
          this.editInspections = this.constructionData['devices'];
          this.con_ocation = this.constructionData['construct_location'];
          this.aff_location = this.constructionData['affected_location'];
          console.log(this.aff_location)
          let locatios = [];
          for (let i in this.con_ocation){
            locatios.push(this.con_ocation[i].label)
          }
          this.constructionData['construct_location']=locatios;
          let affectlocations = [];
          for (let i in this.aff_location){
            affectlocations.push(this.aff_location[i].label)
          }
          this.constructionData['affected_location']=affectlocations;
          this.updatetreeModel.oid = this.constructionData['org_approver_pid'];
          this.queryJurList();
          this.editDataSource = this.constructionData['devices']?this.constructionData['devices']:[];
          if(!this.editDataSource){
            this.editDataSource = [];
            this.editInspections =[];
            this.totalRecords = 0;
          }
          this.editInspections = this.editDataSource.slice(0,10);
          this.totalRecords = this.editDataSource.length;
        })
      }
    })
    this.querylogin();
    this.isButtonValueValid();
  }
  constructionMultipe() {
    this.processService.queryConstructionInfo().subscribe(data =>{
      if(data['施工类型']){
        this.categories = data['施工类型']
      }else{
        this.categories = [];
      }
    });
  }
  clearaffectLocationDialog () {
      this.submitData.affected_location = '';
      this.constructionData['affected_location'] = '';
  }
  onBeforeUpload(event) {
    let token = this.storageService.getToken('token');
    event.formData.append('access_token', token);
  }
  onUpload(event) {
    let xhrRespose = JSON.parse(event.xhr.response);
    if ( xhrRespose.errcode && xhrRespose.errcode === '00000' ) {
      this.submitData.construction_apply_attachments = xhrRespose['datas'];
      this.constructionData['construction_apply_attachments'] = xhrRespose['datas']
      this.message = [];
      this.message.push({severity: 'success', summary: '消息提示', detail: '上传成功'});
    }else {
      this.message = [];
      this.message.push({severity: 'error', summary: '消息提示', detail: `上传失败${xhrRespose.errmsg}`});
    }
  }

  goBack() {
    let sid =  this.constructionData['sid'];
    this.constructionData['status'] = "";
    this.eventBusService.flow.next(this.constructionData['status']);
    this.router.navigate(['../constructionoverview'],{queryParams:{sid:sid,state:'viewDetail',title:'施工总览'},relativeTo:this.route})
  }
//文件上传
  onBasicUploadAuto(event) {
    let res = JSON.parse(event.xhr.responseText);
    let photoUrl = res['datas'];
    console.log(photoUrl);
    let construction_apply_attachments = [];
    for(let i = 0;i<photoUrl.length;i++){
      let temp = photoUrl[i];
      console.log(temp)
      let obj ={};
      obj['path'] = temp['path'];
      obj['file_name'] = temp['file_name'];
      obj['file_size'] = temp['file_size'];
      obj['upload_time'] = temp['upload_time'];
      construction_apply_attachments.push(obj);
    }
    this.submitData.construction_apply_attachments = construction_apply_attachments;
    this.constructionData['construction_apply_attachments'] = construction_apply_attachments;
    console.log( this.submitData.construction_apply_attachments)
  }
  //查询登录人
  querylogin(){
    this.processService.queryPersonal().subscribe(data=>{
      this.personalData = data;

      this.submitData['creator'] = this.personalData['name']
    });
  }
  displayEmitter(event) {
    this.displayPersonel = event;
  }
  dataEmitter(event) {
    console.log(event);
    this.displayPersonel = false;
    if(this.type === 'add'){
      this.submitData.submitter  = event.name;
      this.submitData.submitter_org  = event.organization;
      this.submitData.submitter_phone  = event.mobile;
      this.submitData.submitter_pid = event.pid;
      this.treeModel.oid =  event.oid;
      // this.treeModel.oid =  this.submitData.submitter_pid;
      this.queryJurList();
    }else{
      this.constructionData['submitter']  = event.name;
      this.constructionData['submitter_org']  = event.organization;
      this.constructionData['submitter_phone']  = event.mobile;
      this.constructionData['submitter_pid'] = event.oid;
      this.updatetreeModel.oid =  this.constructionData['submitter_pid'];
      this.queryJurList();
    }
  }
  showPersonMask(type){
    this.type = type;
    this.displayPersonel = !this.displayPersonel;
  }
  showLocationMask(type){
    this.type = type;
    this.displayLocation = !this.displayLocation;
  }
  showAffectMask(){
    this.displayaffectLocation = !this.displayaffectLocation;
  }
  clearTreeDialog () {
    if(this.type === 'add'){
      this.submitData.submitter = '';
      this.submitData.submitter_org = '';
      this.submitData.submitter_phone = '';
    }else{
      this.constructionData['submitter'] = '';
      this.constructionData['submitter_org'] = '';
      this.constructionData['submitter_phone'] = '';
    }
  }
  clearConstructionLocation () {
    if(this.type === 'add'){
      this.submitData.construct_location = ''
    }else{
      this.constructionData['construct_location'] = '';
    }
  }
  //查询人员表格数据
  queryJurList(){
    if(this.viewState === 'add'){
    this.processService.getPersonList(this.treeModel.oid).subscribe(data => {
      this.tableDatas = data;
      this.dropDownData = this.processService.applicationDropdownapprover(this.tableDatas);
      this.submitData.org_approver = this.dropDownData[0]['label']
    })
    }else {
      this.processService.getPersonList(this.updatetreeModel.oid).subscribe(data => {
        this.tableDatas = data;
        this.updatedropDownData = this.processService.applicationDropdownapprover(this.tableDatas);
      })
    }
  }
  addDev(metail){
      this.showAddEquement = false;
      if(this.viewState === 'add'){
        for(let i = 0;i<metail.length;i++){
          this.dataSource.push(metail[i]);
        }
      }else {
        for(let i = 0;i<metail.length;i++){
          this.editDataSource.push(metail[i]);
        }
      }
      this.totalRecords = this.dataSource.length;
      this.inspections = this.dataSource.slice(0,10);
      this.totalRecords = this.editDataSource.length;
      this.editInspections = this.editDataSource.slice(0,10);
  }
  showAddEquementMask(){
    this.showAddEquement = !this.showAddEquement;
  }
  closeAddEquementMask(bool){
    this.showAddEquement = bool;
  }
  closeAddLocationMask(bool){
    this.displayLocation = bool;
  }
  closeaffectLocationMask(bool){
    this.displayaffectLocation = bool;
  }
  deleteStorage(){
    // this.chooseCids = [];
    // this.chooseCids.push(current['ano']);
    for(let i = 0;i<this.selectConstructions.length;i++){
      for(let j = 0;j<this.dataSource.length;j++){
        if(this.selectConstructions[i]['ano']===this.dataSource[j]['ano']){
          this.dataSource.splice(j,1);
          this.inspections = this.dataSource.slice(0,10);
          this.selectConstructions = [];
        }
      }
    }
  }
  updateDeleteStorage(){
    for(let i = 0;i<this.selectConstructions.length;i++){
      for(let j = 0;j<this.editDataSource.length;j++){
        if(this.selectConstructions[i]['ano']===this.editDataSource[j]['ano']){
          this.editDataSource.splice(j,1);
          this.editInspections = this.editDataSource.slice(0,10);
          this.selectConstructions = [];
        }
      }
    }
  }
  loadCarsLazy(event) {
    setTimeout(() => {
      if(this.dataSource) {
        this.inspections = this.dataSource.slice(event.first, (event.first + event.rows));
      }
    }, 0);
  }
  addConstructionOrg(org){
    if(this.viewState === 'add'){
      this.constructionLocation = org;
      this.submitData.construct_location = [];
      for(let i = 0;i<org.length;i++){
        this.submitData.construct_location.push(org[i]['label'])
      }
      this.submitData.construct_location =  this.submitData.construct_location.join('>');
    }else if(this.viewState === 'update'){
      this.constructionLocation = org;
      this.constructionLocation['construct_location'] = [];
      for(let i = 0;i<org.length;i++){
        this.constructionData['construct_location'].push(org[i]['label'])
      }
      this.constructionData['construct_location'] =  this.constructionData['construct_location'].join('>');
    }

    this.displayLocation = false;
  }
 // 影响区域
  addConstructionAffectLocation(org){
    if(this.viewState === 'add'){
      this.affectLocation = org;
      this.submitData.affected_location = [];
      for(let i = 0;i<org.length;i++){
        this.submitData.affected_location.push(org[i]['label'])
      }
      this.submitData.affected_location =  this.submitData.affected_location.join('>');
    }else{
      this.constructionLocation = org;
      this.constructionLocation['affected_location'] = [];
      for(let i = 0;i<org.length;i++){
        this.constructionData['affected_location'].push(org[i]['label'])
      }
      this.constructionData['affected_location'] =  this.constructionData['affected_location'].join('>');
    }
    this.displayaffectLocation = false;
  }
  // 提交
  addConstructionSubmint(submitData,dataSource){
    submitData.construct_location = this.constructionLocation;
    submitData.affected_location = this.affectLocation;
    submitData.devices = dataSource;
    this.processService.addConstructionOrder(submitData).subscribe(()=>{
      this.router.navigate(['../constructionoverview'],{queryParams:{title:'施工总览'},relativeTo:this.route})
    },(err:Error)=>{
      let message ;
      if(JSON.parse(JSON.stringify(err)).status===504){
        message = '似乎网络出现了问题，稍后重试'
      }else{
        message =err
      }
      this.confirmationService.confirm({
        message: message,
        rejectVisible:false,
      })
    })
  };
  // 修改提交
  updateConstructionSubmint(submitData,dataSource){

    this.submitData.construct_location = submitData.construct_location;
    submitData.affected_location = this.affectLocation;
    this.submitData.affected_location = submitData.affected_location;
    submitData.construct_location = this.location;
    submitData.devices = dataSource;
    this.processService.addConstructionOrder(submitData).subscribe(()=>{
      this.router.navigate(['../constructionoverview'],{queryParams:{title:'施工总览'},relativeTo:this.route})
    },(err:Error)=>{
      let message ;
      if(JSON.parse(JSON.stringify(err)).status===504){
        message = '似乎网络出现了问题，稍后重试'
      }else{
        message =err
      }
      this.confirmationService.confirm({
        message: message,
        rejectVisible:false,
      })
    })
  };
  //保存
  addConstructionSave(submitData,dataSource){
    submitData.construct_location = this.constructionLocation;
    submitData.affected_location = this.affectLocation;
    submitData.devices = dataSource;
    this.processService.queryConstructionSave(submitData).subscribe(data=>{
      this.router.navigate(['../constructionoverview'],{queryParams:{title:'施工总览'},relativeTo:this.route})
    },(err:Error)=>{
      let message ;
      if(JSON.parse(JSON.stringify(err)).status===504){
        message = '似乎网络出现了问题，稍后重试'
      }else{
        message =err;
      }
      this.confirmationService.confirm({
        message: message,
        rejectVisible:false,
      })
    })
  };
  updateConstructionSave(submitData,dataSource){
    this.constructionData['construct_location'] = submitData.construct_location;
    submitData.affected_location = this.affectLocation;
    this.constructionData['affected_location'] = submitData.affected_location;
    submitData.devices = dataSource;
    this.processService.queryConstructionMod(submitData).subscribe(data=>{
      this.router.navigate(['../constructionoverview'],{queryParams:{title:'施工总览'},relativeTo:this.route})
    },(err:Error)=>{
      let message ;
      if(JSON.parse(JSON.stringify(err)).status===504){
        message = '似乎网络出现了问题，稍后重试'
      }else{
        message =err;
      }
      this.confirmationService.confirm({
        message: message,
        rejectVisible:false,
      })
    })
  };

  formSave(){
    if(this.viewState === 'add'){
      this.addConstructionSave(this.submitData,this.dataSource);
    }else if(this.viewState === 'update'){
      this.updateConstructionSave(this.constructionData,this.editDataSource);
    }
  }
  formSubmit(){
    if(this.viewState === 'add'){
      this.addConstructionSubmint(this.submitData,this.dataSource);
    }else if(this.viewState === 'update'){
      this.updateConstructionSubmint(this.constructionData,this.editDataSource);
    }
  }
  download() {
    window.open(`${environment.url.management}/${this.file.path}`, '_blank');
  }
  //是否影响业务
  affected(bool){
    console.log(bool);

    if(bool){
      //isaffected = bool
    }
  }
  isButtonValueValid(){
    // return this.submitData.construct_location(this.myForm, name);
    this.submitData.construct_location = '';
  }
}
